package my;

import java.util.Arrays;
import java.util.Collection;

import javax.naming.InitialContext;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(value = Parameterized.class)
public class EJBTest {

	private static ILibrary library;

	@BeforeClass
	public static void setUpClass() throws Exception {
		String ejbName = getLookupName();
		library = (ILibrary) new InitialContext().lookup(ejbName);
		Assert.assertNotNull(library);
		// Assert.assertTrue(library.getBooks().isEmpty());
	}

	// @AfterClass
	// public static void tearDownClass() {
	// for (Book book : library.getBooks()) {
	// library.removeBook(book.getIsbn());
	// }
	// }

	@Parameters
	public static Collection<String[]> data() {
		String[][] data = new String[][] { { "WASAH", "Scary Movie" },
				{ "WTF", "O Mestre do Disfarce" },
				{ "Legend", "Shaolin Soccer" } };
		return Arrays.asList(data);
	}

	private final String isbn;

	private final String title;

	public EJBTest(String isbn, String title) {
		this.isbn = isbn;
		this.title = title;
	}

	@Test
	public void testBook() {
		Assert.assertNull(library.getBook(isbn));

		Assert.assertNotNull(library.addBook(isbn, title));

		Assert.assertNotNull(library.getBook(isbn));

		Assert.assertNotNull(library.updateBook(isbn, isbn));

		Assert.assertNotNull(library.removeBook(isbn));

		Assert.assertNull(library.getBook(isbn));
	}

	private static String getLookupName() {
		// The app name is the EAR name of the deployed EJB without .ear
		String appName = "";

		// The module name is the JAR name of the deployed EJB without the .jar
		String moduleName = "Library";

		// AS7 allows each deployment to have an (optional) distinct name.
		String distinctName = "";

		// The EJB bean implementation class name
		String beanName = Library.class.getSimpleName();

		// Fully qualified remote interface name
		final String interfaceName = ILibrary.class.getName();

		// Create a look up string name
		return "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/"
				+ beanName + "!" + interfaceName;
	}
}
